/**
 * @Author kjprime
 * @description redis4.0数据库模块
 */
const redis = require('redis')

const redis_config = {
    host: '192.168.20.130',
    port: '6379',
    password: '11111111',
    number: 0,
}

const url = `redis://:${redis_config.password}@${redis_config.host}:${redis_config.port}/${redis_config.number}`

const redisClient = redis.createClient({'url': url})

redisClient.on('ready', () => {
    console.log('redis is ready...')
})

redisClient.on('error', err => {
    console.error(err)
})

async function fun(callback, key, value, expireIn){
    return new Promise(async (res, rej) => {
        await redisClient.connect()     // 连接
        let ok = callback(key, value, expireIn)   // 成功ok
        await redisClient.quit()        // 关闭
        try {
            res(ok)
        }catch (err){
            console.log('error=',err.message)
            rej(err)
        }
    })
}

const db = {
    async set(key, value, expireIn){
        return fun(async() => {
            if (expireIn === undefined || expireIn === null){
                return await redisClient.set(key, value)
            }
            expireIn = parseInt(expireIn, 10)
            // 设置键名为 "key" 的值并指定过期时间 expireIn（单位为秒）
            await redisClient.setEx(key, expireIn, value)
        }, key, value, expireIn)
    },
    async get(key){
        return fun(async() => {
            return await redisClient.get(key)
        }, key)
    },
    async del(key){
        return fun(async() => {
            return await redisClient.del(key)
        }, key)
    },
    async keyTtl(key){
        return fun(async() => {
            return await redisClient.ttl(key)
        }, key)
    },
}
/*
 * 运行实例
 */
async function runRedis(){
    await db.set("key3", "value3", 98)
    // await db.set("key5", "value5")
    // console.log(await db.get("key3"))
    console.log(await db.keyTtl("key5"))
    // console.log(await db.get("key5"))
}

runRedis()
